package com.jiangcheng.demo.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.List;

@ServerEndpoint("/chatRoom/{username}")
@Component
public class ChatRoom {

    // 记录当前在线记录数
    private static AtomicInteger onlineCount = new AtomicInteger();

    // 存储每个客户端
    private static CopyOnWriteArraySet<ChatRoom> socketSet = new CopyOnWriteArraySet<ChatRoom>();
    /**
     * 离线消息
     */
    private ConcurrentHashMap<String, List<WebSocketMessageEntity>> offlineMessage = new ConcurrentHashMap<>();

    private Session session;

    private String name;


    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username, EndpointConfig config) {
        this.session = session; // 把每个用户连接成功后的session 存到自身的session上
        socketSet.add(this); // 存储客户端
        addOnlineCount();
        this.name = username;//简易用户名
        try {
            /**
             * 像每一个连接的客户端发送 当前客户端进行了聊天室
             */
            for (ChatRoom socket : socketSet) {
                socket.sendMessage("我是系统发的 >> " + this.name + " 加入了聊天");
            }
            /**
             * 给自己的客户端发送欢迎消息
             */
            this.sendMessage("我是系统发的 >> 欢迎您！你是" + this.name + "，开始聊天吧！");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("有新连接加入！当前在线人数为" + onlineCount);
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println("有消息进来");
        System.out.println("来自客户端的消息，由" + this.name + "发出：" + message);
        String mstemp; // 存放的消息
        /**
         * 对当前所有连接的客户端进行遍历
         */
        for (ChatRoom mySocket : socketSet) {
            System.out.println(this.name);
            /**
             * 判断是否为当前客户端
             */
            if (this.name.equals(mySocket.name)) {
                mstemp = "我" + ">>" + message;
            } else {
                /**
                 * 给其他客户端发送当前客户端发送的消息以及当前客户端的名字
                 */
                mstemp = this.name + ">>" + message;
            }
            /**
             * 给每个客户端发送消息
             */
            try {
                mySocket.sendMessage(mstemp);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) throws IOException {

//        for (WsDemo socket : socketSet) {
//            System.out.println(socket);
//            socket.sendMessage(this.name + " 离开了了群聊");
//        }
        subOnlineCount();
        try {
            socketSet.remove(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("一个用户离开了！当前在线人数" + onlineCount);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("连接发生错误");
        Error error = new Error();
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized void addOnlineCount() {
        onlineCount.incrementAndGet();
    }

    public static synchronized void subOnlineCount() {
        onlineCount.decrementAndGet();
    }
}